package io.xxx.cyb.sync.impl

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import io.xxx.cyb.model.Document
import io.xxx.cyb.model.Store
import io.xxx.cyb.sync.Porter
import io.xxx.cyb.util.dateTimeFormatter
import org.springframework.web.util.UriComponentsBuilder
import java.time.LocalDateTime

/**
 * 淘宝
 */
abstract class TbPorter(sid: String) : Porter(sid) {

    private val httpUrl = "https://39.100.8.158/api"

    override val startPage = 0

    protected fun getResponse(
        store: Store,
        startTime: LocalDateTime,
        endTime: LocalDateTime,
        pageNo: Long = 0,
        path: String,
    ): Any {
        val url = UriComponentsBuilder.fromHttpUrl(httpUrl)
            .path(path)
            .queryParam("sellerId", store.oid)
            .queryParam("startTime", startTime.format(dateTimeFormatter))
            .queryParam("endTime", endTime.format(dateTimeFormatter))
            .queryParam("pageNo", pageNo)
            .toUriString()
        return restTemplate.getForEntity(url, JSONObject::class.java).body!!
    }
}

// 订单
@Suppress("unused")
class TbTradePorter(sid: String) : TbPorter(sid) {

    override fun getCount(store: Store, startTime: LocalDateTime, endTime: LocalDateTime, parameter: Any?): Long {
        return getResponse(store, startTime, endTime, path = "/trades/count").toString().toLong()
    }

    override fun getData(
        store: Store,
        startTime: LocalDateTime,
        endTime: LocalDateTime,
        parameter: Any?,
        pageNo: Long
    ): List<Document> {
        val response = getResponse(store, startTime, endTime, pageNo, "/trades") as List<*>
        return response.map {
            val jsonObject = JSON.parseObject(it.toString())
            Document(jsonObject.getString("tid"), jsonObject, jsonObject.getTimestamp("jdpModified").toLocalDateTime())
        }
    }
}

// 退单
@Suppress("unused")
class TbRefundPorter(sid: String) : TbPorter(sid) {

    override fun getCount(store: Store, startTime: LocalDateTime, endTime: LocalDateTime, parameter: Any?): Long {
        return getResponse(store, startTime, endTime, path = "/refunds/count").toString().toLong()
    }

    override fun getData(
        store: Store,
        startTime: LocalDateTime,
        endTime: LocalDateTime,
        parameter: Any?,
        pageNo: Long
    ): List<Document> {
        val response = getResponse(store, startTime, endTime, pageNo, "/refunds") as List<*>
        return response.map {
            val jsonObject = JSON.parseObject(it.toString())
            Document(
                jsonObject.getString("refundId"),
                jsonObject.getString("tid"),
                jsonObject,
                jsonObject.getTimestamp("jdpModified").toLocalDateTime()
            )
        }
    }
}